package com.cyk.comicforumjava.demos.WebSocket;

import com.cyk.comicforumjava.demos.enits.Message;
import com.cyk.comicforumjava.demos.mapper.MessageMapper;
import com.cyk.comicforumjava.demos.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

public class MyWebSocketHandler  extends TextWebSocketHandler {

    private Map<String, WebSocketSession> sessions = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接建立");
    }



    @Autowired
    MessageMapper messageMapper;
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String payload = message.getPayload();
        if (payload.startsWith("userId:")) {
            // 解析用户 ID
            String userId = payload.substring("userId:".length());
            sessions.put(userId, session);
            System.out.println("已存储用户 ID: " + userId);
            ThreadLocalUtil.set(Long.parseLong(userId));
            System.out.println("当前用户ID"+ThreadLocalUtil.get());
            sendMessageToUser("后端",userId, "后端发来回复");
        }else{
            System.out.println("接收到消息"+payload); // 添加日志输出，打印接收到的消息内容

            String[] parts = payload.split(":");
            String targetUserId = parts[0];
            String content = parts[1];
            String senderString = null;
            Long senderID= null;
            try{
                senderID= Long.parseLong(parts[2]);
                senderString=parts[2];
            }catch (Exception e){
                content=content+":"+parts[2];
                senderID=Long.parseLong(parts[3]);
                senderString=parts[3];
            }

            Message chatMessage = new Message();
            chatMessage.setSenderId(senderID);
            chatMessage.setUserlId(Long.parseLong(targetUserId));
            chatMessage.setContent(content);
            chatMessage.setCreateTime(LocalDateTime.now());
            chatMessage.setKind("chat");
            messageMapper.addMessage(chatMessage);
            sendMessageToUser(senderString,targetUserId, content);
        }

    }

    public void sendMessageToUser(String sender,String userId, String message) throws IOException {
        System.out.println("用户:"+sender+"发送消息给用户 ID: " + userId + ", 消息内容: " + message);
        WebSocketSession targetSession = sessions.get(userId);
        if (targetSession != null && targetSession.isOpen()) {
            targetSession.sendMessage(new TextMessage(message));
        }
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            if (entry.getValue() == session) {
                sessions.remove(entry.getKey());
                break;
            }
        }
    }
}